<?php

namespace app\common\model;

use think\facade\Session;
use think\Model;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class User extends Model
{
    public function login($username, $password)
    {
        $username = trim($username);
        $password = trim($password);
        $userInfo = $this->where('username', $username)->find();
        if (empty($userInfo) || empty($password)) {
            return false;
        }
        //密码验证
        if (encrypt_password($password) != $userInfo['password']) {
            return false;
        }
        Session::set('main_user', $userInfo);
        return true;
    }
    public function reg($data)
    {
        $cost = new Cost();
        if ($this->where('username', $data['username'])->find()) {
            return false;
        }
        $c = $cost->getinfo(6);
        if($c == 1){
            if (!Session::has('authCodeMT')){
                return '请获取手机验证码！';
            }
            $vcode = Session::get('authCodeMT');
            if($vcode != $data['smscode']){
                return '手机验证码错误';
            }
        }

        $data['password'] = encrypt_password($data['password']);
        // 增加初始金额
        $cost = new Cost();
        $data['balance'] = $cost->getinfo(1);

//        if (Session::has('invite')) {
//            $data['invite'] = Session::get('invite');
//        }
        if ($this->save($data)) {
            return true;
        }
        return '注册失败';
    }
    //增加余额
    public function inc_balance($num)
    {
        if ($this->setInc('balance', $num)) {
            return true;
        } else {
            return false;
        }
    }
    //读取用户信息 并更新Session
    public function getinfo($id = '')
    {
        if ($id == '') {
            $id = Session::get('main_user')['Id'];
            $info = $this->where('Id', $id)->find();
            Session::set('main_user',$info);
            return $info;
        }
        $info = $this->where('Id', $id)->find();
        return $info;
    }
    //后台 - 获取用户列表
    public function getuserlist($page, $limit, $key)
    {
        if (isset($key)) {
            $cate_list = $this->where('username', 'like', "%$key%")->limit($page, $limit)->order('Id', 'desc')->select();
            $list_number = $this->where('username', 'like', "%$key%")->count();
        } else {
            $cate_list = $this->limit($page, $limit)->order('Id', 'desc')->select();
            $list_number = $this->count();
        }
        $msg = '';
        if ($cate_list->isEmpty()) {
            $msg = '暂无数据';
        }
        return json_l($cate_list->toArray(), $list_number, $msg);
    }
    //删除用户
    public function del($id)
    {
        if ($this->where('Id', $id)->delete()) {
            return true;
        } else {
            return false;
        }
    }
    //更新用户信息
    public function up_user($data, $id)
    {
        $data['password'] = encrypt_password($data['password']);
        if ($this->save($data, ['Id' => $id])) {
            return true;
        } else {
            return false;
        }
    }
    //是否登陆
    public function islogin()
    {
        if (Session::has('main_user')) {
            return true;
        }
        return false;
    }
    //开通vip用户
    public function op_vip($data,$is_admin = 0)
    {
        if($is_admin == 1){//后台 就需要传入操作的用户id
            $user_info = $this->where('Id', $data['id'])->find();
        }else{
            $user_info = $this->getinfo();
            //用户前台自主申请 扣除余额
            $this->where('Id',$user_info['Id'])->setDec('balance',$data['price']);
        }
        $cost = new Cost();
        //首次开通
        //time 为 几个月
        $data['time'] = $data['time'] * 31;

        if ($user_info['grade'] == 0) {
            $new_time =  date('Y-m-d H:i:s', strtotime("+" . $data['time'] . " day"));
            if ($this->where('Id', $user_info['Id'])->update(['end_time' => $new_time, 'grade' => 1])) {
                return true;
            }
            return false;
        } else if ($user_info['grade'] == 1) {
            //增加时间
            $now_time = $user_info['end_time']; //结束时间
            $new_time = date('Y-m-d H:i:s', strtotime("$now_time +" . $data['time'] . " day"));
            if ($this->where('Id', $user_info['Id'])->update(['end_time' => $new_time])) {
                return true;
            }
            return false;
        }
        return false;
    }

    //修改密码
    public function up_pass($data, $id)
    {
        $u_info = $this->where('Id', $id)->find();
        if ($u_info['password'] != encrypt_password($data['old_pass'])) {
            return '原密码不正确！';
        }
        if (encrypt_password($data['old_pass']) == encrypt_password($data['new_pass'])) {
            return '新密码与旧密码相同!';
        }
        if ($this->where('Id', $id)->update(['password' => encrypt_password($data['new_pass'])])) {
            return true;
        }
        return '修改失败';
    }

    /**
     * 后台充值积分 直接充值积分
     * @return void
     */
    public function admin_pay($data){
        if($this->where('Id',$data['id'])->setInc('balance',$data['price'])){
            $log = new PayLog();
            $log->in_log(GetOrder(),$data['id'], $data['price'],3);
            return true;
        }
        return false;
    }

    /**
     * 发送短信验证码
     * @param string $phoneNumber
     * @return void
     */
    public function sendAliDaYuAuthCode($phoneNumber = '151xxxxxxx3')
    {
        if(User::where('username',$phoneNumber)->find()){
            return '该号码已注册！';
        }


        $cost = new Cost();
        $c = $cost->getinfo(0);

        $accessKeyId = $c['al_KeyId'];
        $accessSecret = $c['al_Secret']; //注意不要有空格
        $signName = $c['al_signName']; //配置签名
        $templateCode = $c['al_templateCode'];//配置短信模板编号
        //TODO 随机生成一个6位数
        $authCodeMT = mt_rand(100000,999999);
        //TODO 短信模板变量替换JSON串,友情提示:如果JSON中需要带换行符,请参照标准的JSON协议。
        $jsonTemplateParam = json_encode(['code'=>$authCodeMT]);
        AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)
            ->regionId('cn-hangzhou')
            ->asGlobalClient();
        try {
            $result = AlibabaCloud::rpcRequest()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => [
                        'RegionId' => 'cn-hangzhou',
                        'PhoneNumbers' => $phoneNumber,//目标手机号
                        'SignName' => $signName,
                        'TemplateCode' => $templateCode,
                        'TemplateParam' => $jsonTemplateParam,
                    ],
                ])
                ->request();
            $opRes = $result->toArray();
            //dump($result);die;
            //print_r($opRes);
            if ($opRes && $opRes['Code'] == "OK"){
                
                //进行Cookie保存
                Session::set('authCodeMT',$authCodeMT);
                return true;
            }
        } catch (ClientException $e) {
            return '发送失败 (请联系管理员)';
            //echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            return '发送失败 (请联系管理员)';
            //echo $e->getErrorMessage() . PHP_EOL;
        }
    }
}
